from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
import logging


class BasePage:

    def __init__(self, driver: WebDriver = None):
        logging.info(f"开始初始化页面 driver={driver}")
        if driver:
            self.driver = driver
            logging.info("页面初始化完成")
        else:
            logging.info("页面初始化失败")
            raise SystemError

    def find(self, by, locator=None):
        logging.info(f"进入find方法，开始查找元素，参数by={by}, 参数locator={locator}")
        if locator:
            ele = self.driver.find_element(by, locator)
        else:
            ele = self.driver.find_element(*by)

        logging.info(f"退出find方法，查找的元素是{ele}")
        return ele

    def find_all(self, by, locator):
        logging.info(f"进入finds方法，开始查找元素，参数by={by}, 参数locator={locator}")
        if locator:
            eles = self.driver.find_elements(by, locator)
        else:
            eles = self.driver.find_elements(*by)

        logging.info(f"退出finds方法，查找到{len(eles)}个元素")
        return eles

    def find_and_click(self, by, locator=None):
        logging.info(f"进入find_and_click方法, 参数by={by}, 参数locator={locator}")
        self.swipe_and_find(by, locator).click()
        logging.info(f"点击完成，退出find_and_click方法")

    def find_and_input(self, text, by, locator=None):
        logging.info(f"进入find_and_input方法, 参数by={by}, 参数locator={locator}")
        self.find(by, locator).send_keys(text)
        logging.info(f"输入文本{text}完成, 退出find_and_input方法")

    def get_element_text(self, by, locator=None):
        logging.info(f"get_element_text方法, 参数by={by}, 参数locator={locator}")
        return self.find(by, locator).text

    def swipe_and_find(self, by, locator=None, retry=3):
        logging.info(f"进入swipe_and_find方法, 参数by={by}, 参数locator={locator}，查找{retry}次")
        window_size = self.driver.get_window_rect()
        height = window_size["height"]
        width = window_size["width"]

        for i in range(retry):
            try:
                logging.info(f"开始第{i+1}次查找")
                return self.find(by, locator)
            except:
                logging.info(f"第{i + 1}次没有找到元素")
                self.driver.swipe(width / 2, height * 0.9, width / 2, height * 0.1)

            if i == retry-1:
                logging.info(f"退出swipe_and_find方法， 没有在{retry}次内找到指定元素")
                raise NoSuchElementException(f"没有在{retry}次内找到指定元素")

    def back(self):
        logging.info("进入back方法")
        self.driver.back()
        logging.info("退出back方法")